'use strict';

const Controller = require('egg').Controller;
// 发送支付功能
const AlipaySDK = require('alipay-sdk').default
// 将支付信息 formdata 包裹住
const AlipayFormData = require('alipay-sdk/lib/form').default

class PayController extends Controller {
    async alipay() {
        const { ctx, config } = this;
        const alipaySdk = new AlipaySDK({
            appId: '2021000118644868', // 你自己的沙箱环境的appId
            privateKey: "MIIEpAIBAAKCAQEAnvhCpoJL+3NGJvgmfaySUsDUoHIKS3HqwrAlsp4jZoMIVSWOUWKO9z6TD9h/mKpS7HUaTucvXkz0GydQeu+KoqrMNdhTvm8c1Kx/Fanv6ryl4nAzq9+uSflbC+tobKAZE6eU0pYPkHsfPzit4FiHE1+CGpyNiEv0apuSIEbuaNtXLnmtRZVZf4oh+71+/tJLF+5gr8ssqadEgmLfraewMVl0vJrU9slqneMPUYG7pbinF97bx+tRxnhR4iE/73LTwQtClZj4GzVwjW+17Wg2l2TwN58tC1jpLJSvr2RMucCusZKdnh8BId8RBY4P6p2I1y4HG8oDfvCef40IqTxMFQIDAQABAoIBAC0d+IyZXkc3KCnXM9VnLQAfijkfJJzU7/PhWlGfYBywA6Vmy0V922WAdOyCXXROospJUfYi1ubEoGM0fTrm0Unpf5uokdvyXRRfAJJ9cIIGmG3zujaFfUmxY422eiSaK4PQhARgYnp29x9STsblWTC+YoZ6+BA+vlejX42ZlABeC4Uyt00siT+/OpGX30Y5EH9RpRv76zek6NHiK8zsbef6at9HbV9W3j06Tq6N/pFMuhvmnxps+asKMx3eLjOz9rOdEeLmhJBi7vxgP/bZRfsKLZSuc+e3SvKLIFpWfyhVVbiK7bWv/1cxHa8Z1FYh4XYqS2ltFeuHuKl1IzzJmwECgYEA89uH3EWZ2oPoV6NXCRgtDUUcdL5w6ADPPONBddbke5n64ATFMNddXEFTJYnsZ2thPYqYokZkHWtrYWg+o4lNN86HauKTLp4IfBm3Z240QEhtdJRrQQaFxYsh0m2+vW6SZUEQibiyNbAVnWNHWBE/w+Iiu+qGwRUPje16auODEykCgYEApuKowNDNtoc95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vr2RMucCusZKdnh8BId8RBY4P6p2I1y4HG8oDfvCef40IqTxMFQIDAQAB', // 支付宝公钥（不是应用公钥）
            gateway: 'https://openapi.alipaydev.com/gateway.do', // 网关地址
            timeout: 5000, // 网关超时时间
            camelcase: true // 是否把网关返回的下划线 key 转换为驼峰写法
        })

        const formData = new AlipayFormData();

        formData.setMethod('get'); //请求方式
        formData.addField('appId', '2021000118644868'); //用户id
        formData.addField('charset', 'utf-8'); //编码格式
        formData.addField('signType', 'RSA2');//注册信息格式
        formData.addField('bizContent', { //设置商户信息
            outTradeNo: new Date() * 1 + '', // 【必选】商户订单号：64个字符内，包含数字，字母，下划线；需要保证在商户端不重复
            productCode: 'FAST_INSTANT_TRADE_PAY', // 【必选】销售产品码(二维码)，目前仅支持FAST_INSTANT_TRADE_PAY
            totalAmount: '10000', // 【必选】订单总金额，精确到小数点后两位
            subject: 'aaaaaaaaaaaaaaaaaa', // 【必选】 订单标题
            body: 'bbbbbbbbbbbbbbbbb' // 【可选】订单描述
        })
        console.log('formData:===============', formData)
        /**
         * exec对应参数：
         * method（调用支付宝api）
         * params（api请求的参数（包含“公共请求参数”和“业务参数”））
         * options（validateSign，formData，log）
         *
         * 统一下单支付 exec
         */
        ctx.body = await alipaySdk.exec('alipay.trade.page.pay', {}, { formData })
    }
}

module.exports = PayController;